package com.itheima.grow.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * description
 *
 * @Author:weiwei.xie
 * @Date 2022/11/11
 */
@Slf4j
public class CommunalTool {
    /**
     * Map中的null转换成""(空串)
     *
     * @param map 转换之前的数据
     * @return 返回 Map<String,Object>
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Map<String, Object> map) throws Exception {
        return JSONObject.parseObject(objectToString(map), Map.class);
    }

    // fistJson 的一个过滤器
    private static ValueFilter filter = new ValueFilter() {
        @Override
        public Object process(Object obj, String s, Object v) {
            if (v instanceof Date) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                return simpleDateFormat.format(v);
            } else {
                if (v == null) {
                    return "";
                } else {
                    return v;
                }
            }
        }
    };

    /**
     * 将对象转换为json格式的字符串
     *
     * @param obj
     * @return String
     */
    public static String objectToString(Object obj) {
        // JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
        return JSON.toJSONString(obj, filter, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNullStringAsEmpty);
    }

}
